package com.xianyl.libsforandroid.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 关于流的工具类
 * @author xianyl
 * @date 2015-3-2 下午9:38:07
 */
public class StreamUtil {
	

	/**
	 * 从流中读取字节数组
	 * @param inputStream 数据输入流
	 * @return 返回一个字节数组,如果流为空，返回空
	 * @throws IOException 
	 */
	public static byte[] readByteArray(InputStream inputStream) throws IOException {
		if(inputStream == null){
			return null;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int len = -1;
		while ((len = inputStream.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		baos.flush();		
		baos.close();			
		inputStream.close();
		return baos.toByteArray();
	}

	/**
	 * 从流中读取字符串
	 * @param charsetName 编码
	 * @param inputStream 数据输入流
	 * @return 字符串
	 * @throws IOException 
	 */
	public static String readString(String charsetName, InputStream inputStream)
			throws IOException {
		byte[] data = readByteArray(inputStream);
		return new String(data, charsetName);
	}

}
